//
//  SelectionViewController.m
//  UGoods
//
//  Created by dllo on 16/1/15.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "SelectionViewController.h"
#import "LHAFNetworkTool.h"
#import "BaseTableView.h"
#import "BaseLabel.h"
#import "FindModel.h"
#import "GoodsTableViewCell.h"
#import "FeatureTableViewCell.h"
#import "BuyerTableViewCell.h"
#import "CarouselImageView.h"
#import <MJRefresh.h>
#import "BuyDetailViewController.h"
#import "FeatureDetailViewController.h"
#import "ConstantsDefine.h"
#import <AFNetworking.h>
#import <SDCycleScrollView.h>
@interface SelectionViewController ()<UITableViewDataSource, UITableViewDelegate,
BuyerTableViewCellDelegate, SDCycleScrollViewDelegate>

@property (nonatomic, retain) BaseTableView *tableView;
@property (nonatomic, retain) NSMutableArray *imageArray; /**< 轮播图数组 */
@property (nonatomic, retain) NSMutableArray *sectionArray; /**< 储存section key值的数组 */
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page; /**< 上拉加载的page值 */
//@property (nonatomic, assign)BOOL isUpLoading;//用来标记上拉还是下拉

@end

@implementation SelectionViewController

- (void)dealloc
{
    Block_release(_webDetail);
    Block_release(_topDetail);
    Block_release(_buyDetail);
    Block_release(_featureDetail);
    Block_release(_buyerDetail);
    [_tableView release];
    [_imageArray release];
    [_sectionArray release];
    [_dataArray release];
    [super dealloc];
}

// 数据解析
- (void)handleData {
    NSString *str =[NSString stringWithFormat:@"http://api.ujipin.com/v4/feature?channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=0&plantform=iphone&version=314&pageNum=20&format=json&page=%ld", self.page];
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"feature"];
        NSMutableArray *mArray = [NSMutableArray arrayWithArray:array];
     
        [self.sectionArray addObjectsFromArray:mArray];
        
        NSArray *splashesArray = resposeObject[@"data"][@"splashes"];
        for (NSDictionary *dic in splashesArray) {
            [self.imageArray addObject:dic[@"img_url"]];
            
        }
        self.dataArray = [FindModel modelHandleWithArray:splashesArray];
       
        // 轮播图
        SDCycleScrollView *cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 180 * HEIGHT) imageURLStringsGroup:self.imageArray];
        // 签代理
        cycleView.delegate = self;
        // page小圆点颜色
        cycleView.currentPageDotColor = [UIColor redColor];
        // 占位图
        cycleView.placeholderImage = [UIImage imageNamed:@"place"];
        // 自动播放时间
        cycleView.autoScrollTimeInterval = 5;
        // 添加轮播图
        self.tableView.tableHeaderView = cycleView;
        
        [self.tableView reloadData];
        
        // 刷新
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        // 数据全部加载完成时需要判断的方法
        if (mArray.count == 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        NSLog(@"section:%ld", self.sectionArray.count);
        
        // 当前网络判断
        [self handleJudgeNetworkStatus];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败：%@", error);
    }];
}

// 当前网路判断
- (void)handleJudgeNetworkStatus {
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
                
            case AFNetworkReachabilityStatusUnknown: // 未知网络
            {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前为未知网络" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
                
            }
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
            {

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲!无网络!请查看网络设置" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
                break;
                
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
            {

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲!正在使用手机3G/4G网" preferredStyle:UIAlertControllerStyleAlert];
                /* 创建action对象 */
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    
                }];
                
                /* alert添加action对象 */
                [alert addAction:actionConfirm];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];

                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
            {
                //                NSLog(@"WIFI");
                
                break;
            }
        }
    }];
    
    // 3.开始监控
    [manager startMonitoring];
}

// 轮播图点击事件
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    FindModel *model = [self.dataArray objectAtIndex:index];
    NSLog(@"%@", model.type);
    // 通过typ值
    if ([model.type isEqualToNumber:@6]) {
        self.webDetail(model);
    } else if ([model.type isEqualToNumber:@5] ) {
        self.topDetail(model);
    } else {
        return;
    }
}

// 下拉刷新
- (void)addHeaderRefresh {
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        
        [self.imageArray removeAllObjects];
        [self.sectionArray removeAllObjects];
        
        self.page = 1;
        [self handleData];
    }];
    // 设置普通状态的动画图片
    NSArray *idleImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态
    NSArray *pullingImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    for (NSInteger i = 0; i < 24; i++) {
        [refreshingImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading_%ld", i]]];
    }
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    // 设置所有数据加载完毕的动画图片
    NSArray *NoMoreDataImages = @[[UIImage imageNamed:@"loading_0"]];
    [header setImages:NoMoreDataImages forState:MJRefreshStateNoMoreData];
    
    self.tableView.mj_header = header;
    
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 隐藏状态
    header.stateLabel.hidden = YES;
    
//    [self.tableView.mj_header beginRefreshing];
}

// 上拉加载
- (void)addFooterRefresh {

    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page += 1;
        [self handleData];
    }];
}

// 创建tableView
- (void)createTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 64 * HEIGHT, self.view.frame.size.width, self.view.frame.size.height - 64 * HEIGHT - 49 * HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[GoodsTableViewCell class] forCellReuseIdentifier:@"cell1"];
    [_tableView registerClass:[FeatureTableViewCell class] forCellReuseIdentifier:@"cell2"];
    [_tableView registerClass:[BuyerTableViewCell class] forCellReuseIdentifier:@"cell3"];
}

// 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArray.count;
}

// 每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dic = self.sectionArray[section];
    NSArray *array = dic[@"list"];
//    NSLog(@"%@", [dic[@"daily"] stringValue]);
    return array.count;
}

// 自定义分区头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSDictionary *dic = _sectionArray[section];
    NSString *str = [dic[@"daily"] stringValue];
    NSTimeInterval time=[str doubleValue]+28800;//因为时差问题要加8小时 == 28800 sec
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
//    NSLog(@"date:%@",[detaildate description]);
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"MM.dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    
    BaseLabel *dateLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20 * HEIGHT)];
    dateLabel.textAlignment = NSTextAlignmentCenter;
    dateLabel.backgroundColor = [UIColor clearColor];
    dateLabel.font = [UIFont fontWithName:@"Zapfino" size:10 * WIDTH];
    dateLabel.text = currentDateStr;
    return dateLabel;
}

// 头部高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 25 * HEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01; // 因为要取消footView 所以设一个很小的高度
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.sectionArray[indexPath.section];
    NSArray *array = dic[@"list"];
    FindModel *model = [FindModel modelWithDic:array[indexPath.row]];
    
    // 通过type_id区分cell
    if ([model.type_id isEqualToNumber:@5]) {
        // @5/ @4
        GoodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.model = model;
        return cell;
        
    } else if ([model.type_id isEqualToNumber:@1]) {
        
        FeatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell.model = model;
        return cell;
        
    } else if ([model.type_id isEqualToNumber:@2]) {
     
        BuyerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        cell.model = model;
        cell.delegate = self;
        
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        return cell;
    }
}

/**
 *  协议方法 实现传值和跳转页面
 *
 *  @param str 传值ID用于拼接网址
 */
- (void)pushBuyDetailWithStr:(NSString *)str {
    BuyDetailViewController *buy = [[[BuyDetailViewController alloc] init] autorelease];
    buy.goods_id = [NSString stringWithFormat:@"%@", str];
    UIViewController *responder = (UIViewController *)self.nextResponder.nextResponder;
    NSLog(@"%@", responder);
    [responder.navigationController pushViewController:buy animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.sectionArray[indexPath.section];
    NSArray *array = dic[@"list"];
    FindModel *model = [FindModel modelWithDic:array[indexPath.row]];
// 通过type_id区分cell
    if ([model.type_id isEqualToNumber:@5]) {
        return 250 * HEIGHT;
    } else if ([model.type_id isEqualToNumber:@1]) {
        return 250 * HEIGHT;
    } else if ([model.type_id isEqualToNumber:@2]) {
        return 250 * HEIGHT;
    } else {
        return 50 * HEIGHT;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dic = self.sectionArray[indexPath.section];
    NSArray *array = dic[@"list"];
    FindModel *model = [FindModel modelWithDic:array[indexPath.row]];
    if ([model.type_id isEqualToNumber:@5]) {
        self.buyDetail(model);
    } else if ([model.type_id isEqualToNumber:@1]) {
        self.featureDetail(model);
    } else if ([model.type_id isEqualToNumber:@2]) {
        self.buyerDetail(model);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.page = 1;
    self.dataArray = [NSMutableArray array];
    self.sectionArray = [NSMutableArray array];
    self.imageArray = [NSMutableArray array];

    [self handleData];
    [self createTableView];
    [self addHeaderRefresh];
    [self addFooterRefresh];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
